<?php

namespace App\Models\User;

use App\Models\Index\LiveMovie;
use Illuminate\Database\Eloquent\Model;

class LiveUserCollect extends Model
{
    public $table = 'live_user_collect';
    public $timestamps = false;

    public function getCreatedTimeAttribute($val)
    {
        return date('Y-m-d',$val);
    }

    #更新或创建收藏记录
    public static function createOrUpdate($user_id,$movie_id)
    {
        $collect  = self::query()->where('user_id','=',$user_id)->where('movie_id','=',$movie_id)->first();
        if (empty($collect)) {
            $flag = self::insert([
                        'user_id'       => $user_id,
                        'movie_id'      => $movie_id,
                        'created_time'  => time(),
                    ]);
            LiveMovie::incCollectById($movie_id);
        } else {
            $collect->status = !$collect->status;
            $flag = $collect->save();
        }
        if (empty($flag)) {
            return false;
        }
        return true;
    }

    #根据用户id获取电影列表
    public static function getMovieByUserId($user_id)
    {
        $data = self::with('movieList')
                    ->where('user_id','=',$user_id)
                    ->where('status','=',1)
                    ->paginate(15)
                    ->toArray();
        if (empty($data)) {
            return [];
        } else {
            return $data;
        }
    }

    #关联电影表
    public function movieList()
    {
        return $this->hasOne(LiveMovie::class,'id','movie_id')->withDefault();
    }
}
